import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';

import { BASE_URL } from '../../config';

interface ProductSearchState {
  loading: boolean;
  error: string | null;
  data: any;
  pagination: any;
}

const initialState: ProductSearchState = {
  loading: true,
  error: null,
  data: null,
  pagination: null
};

// 创建异步任务
export const getProductSearch = createAsyncThunk(
  'productSearch/getProductSearch', // 命名空间
  async (paramaters: {
    keywords: string;
    nextPage: number | string;
    pageSize: number | string;
  }) => {
    let url = `${BASE_URL}/search?pageNumber=${paramaters.nextPage}&pageSize=${paramaters.pageSize}`;
    if (paramaters.keywords) {
      url += `&keyword=${paramaters.keywords}`;
    }
    const resp = await axios.get(url);
    return {
      data: resp.data,
      pagination: {
        currentPage: 1,
        totalCount: 150,
        pageSize: 10
      }
    };
  }
);

export const productSearchSlice = createSlice({
  name: 'productSearch',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getProductSearch.pending, (state) => {
        state.loading = true;
      })
      .addCase(getProductSearch.fulfilled, (state, action) => {
        state.loading = false;
        state.data = action.payload.data;
        state.pagination = action.payload.pagination;
      })
      .addCase(getProductSearch.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as any;
      });
  }
});
